// 公共方法
let plat = 'mp-weixin';
let lang = getApp().globalData.lang
import chatInterceptor from "@/common/chatInterceptor"
import store from "@/store/index.js"
import {
	HTTP_REQUEST_URL,
	IMAGE_URL,
	IM_URL,
	PERFIX,
	kfs,
	LOCALE
} from "@/config/app"

import Vue from 'vue'
//国际化
import RU from '@/lang/ru-RU.json'
import CN from '@/lang/zh-CN.json'
import VueI18n from 'vue-i18n'
const messages = {
	'ru': RU,
	'zh': CN,
}
let i18nConfig = {
	locale: LOCALE, // 获取已设置的语言
	messages,
	silentTranslationWarn: true, // 去除国际化警告
}
Vue.use(VueI18n)
let i18n = new VueI18n(i18nConfig)
Vue.config.productionTip = false
Vue.prototype._i18n = i18n
let app2 = new Vue({
	i18n
})

console.log(app2)
//import app from '@/main'

// #ifdef APP-PLUS
import {
	TUIStore,
	StoreName,
	TUIConversationService
} from "@tencentcloud/chat-uikit-engine";
// #endif

// #ifdef WEB
import {
	TUIStore,
	StoreName,
	TUIConversationService
} from "@tencentcloud/chat-uikit-engine";
// #endif

export function platForm() {
	let plat_local = uni.getStorageSync('plat');
	if (plat_local) {
		plat = plat_local
	} else {
		uni.getSystemInfo({
			success: function(res) {
				if (res.uniPlatform === 'app') {
					plat = 'app'
				} else if (res.uniPlatform === 'web') {
					plat = 'web'
				} else if (res.uniPlatform === 'mp-weixin') {
					plat = 'mp-weixin'
				}
				uni.setStorage({
					key: 'plat',
					data: plat
				})
			}
		});
	}
}

/**
 * 判断是否授权并返回openid
 * @returns {any|boolean}
 */
export function getOpenid(vm) {
	platForm()
	console.log('plat', plat)
	if (plat === 'web') {
		return '';
	} else if (plat === 'app') {
		return '';
	} else {
		return new Promise(function(resolve, reject) {
			let mp_openid = uni.getStorageSync('mp_openid');
			if (mp_openid && mp_openid !== '') {
				resolve(mp_openid)
			} else {
				wechatMpAuth(vm).then(res => {
					mp_openid = res
					resolve(mp_openid)
				})
			}
		})
	}
}

/**
 * 小程序授权
 * @param vm uView实例
 */
function wechatMpAuth(vm) {
	return new Promise(function(resolve, reject) {
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				console.log(loginRes);
				// 获取openid
				vm.api.user.getOpenidByCode({
					code: loginRes.code
				}).then(res => {
					console.log('getOpenid-res', res)
					let mp_openid = res
					uni.setStorage({
						key: 'mp_openid',
						data: mp_openid
					})
					resolve(mp_openid)
				}).catch(err => {
					console.log(err);
				})
			}
		});
	})
}

//判断头像是否为base64
export const isBase64 = (str) => {
	if (!str) return
	let str1 = str;
	if (typeof str == 'object') {
		str1 = str['url']
	}
	return !!(str1.includes("data:image") && str1.includes(";base64,"));
}
//拼接前缀url
export const ImageUrl = (url) => {
	return isBase64(url) ? url : IMAGE_URL + url
}
//毫秒转时间(秒和毫秒）
export const time = (type = "MS", date1, str = "year") => {
	if (type === "S") date1 = date1 * 1000 //秒
	let year = new Date(date1).getFullYear();
	let month = (new Date(date1).getMonth() + 1) > 9 ? (new Date(date1).getMonth() + 1) : '0' + (new Date(date1)
		.getMonth() + 1);
	let date = new Date(date1).getDate() > 9 ? new Date(date1).getDate() : '0' + new Date(date1).getDate();
	let hours = new Date(date1).getHours() > 9 ? new Date(date1).getHours() : '0' + new Date(date1).getHours();
	let minutes = new Date(date1).getMinutes() > 9 ? new Date(date1).getMinutes() : '0' + new Date(date1)
		.getMinutes();
	let seconds = new Date(date1).getSeconds() > 9 ? new Date(date1).getSeconds() : '0' + new Date(date1)
		.getSeconds();
	if (str === "year") {
		return `${year}.${month}.${date} ${hours}:${minutes}:${seconds}`
	}
	if (str === "date") {
		return `${year + `-` + month + `-` + date}`
	}
	return `${year + str + month + str + date} ${hours}:${minutes}:${seconds}`
}
//判断是否为对象
export const isObject = (obj) => {
	return Object.prototype.toString.call(obj) === '[object Object]'
}
//用于组件cardReveal数据的处理
export const exitCard = (template = [], data = {}) => {
	if (getApp().globalData.lang == 'zh') {
		i18nConfig = {
			locale: 'zh', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	} else {
		i18nConfig = {
			locale: 'ru', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	}

	//判断传进来的模版是否为空
	if (template.length === 0 || !Array.isArray(template)) {
		return []
	}
	//判断是否为对象
	if (!isObject(data)) {
		return []
	}
	template.forEach((item, index) => {
		//根据key来找到对应的对象
		let arr = item.key.split('.')
		let obj = data;
		for (let i in arr) {

			if (['mergename'].indexOf(arr[i]) !== -1) {
				obj = obj[app2.$i18n.t("item.city." + arr[i])]
			} else if (['username', 'identity_name'].indexOf(arr[i]) !== -1) {
				obj = obj[app2.$i18n.t("item.user." + arr[i])]
			} else if (['title', 'con_text', 'name', 'content', 'desc', 'introduction', 'person_name',
					'goods_num', 'goods_weight', 'goods_volume', 'show_text', 'mode_value', 'company_name',
					'car_l', 'car_w', 'car_h', 'industry', 'skill', 'con', 'speed_ranking', 'price_ranking',
					'num_ranking'
				].indexOf(arr[i]) !== -1) {
				obj = obj[app2.$i18n.t("item." + arr[i])]
			} else {
				obj = obj[arr[i]]
			}
		}
		//判断是否为数组（数组一定为图片）
		if (Array.isArray(obj)) {
			obj.forEach(it => {
				template[index].images.push(ImageUrl(it.url))
			})
		} else {
			//判断是否为图片
			if (item.isIcon) {
				obj.split(',').forEach(immma => template[index].images.push(ImageUrl(immma)))
			}
			//处理时间戳
			if (item.isTimer) {
				template[index].message = time("S", obj) || app2.$i18n.t('')
			} else {
				template[index].message = obj || app2.$i18n.t('')
			}

		}

	})
	return template
}

export function goImTUIConversation(vm) {
	var mobile = uni.getStorageSync('mobile');

	if (getApp().globalData.lang == 'zh') {
		i18nConfig = {
			locale: 'zh', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	} else {
		i18nConfig = {
			locale: 'ru', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	}

	// 获取token
	if (!mobile) {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	}
	// 跳转IM - webview
	vm.$u.route({
		url: "/pages/message/im/im",
		params: {
			type: "list",
			mobile: mobile
		}
	})
}




export async function createC2CConversation(to_mobile, vm, iskf = false) {
	// 即时聊天权限与业务控制
	const interceptorRes = await chatInterceptor(vm);
	if (!interceptorRes) return;
	var that = this
	var mobile = uni.getStorageSync('mobile');

	console.log('发送方的手机' + mobile, '接收者手机号' + to_mobile)
	if (getApp().globalData.lang == 'zh') {
		i18nConfig = {
			locale: 'zh', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	} else {
		i18nConfig = {
			locale: 'ru', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	}
	console.log(app2)
	// 获取token
	if (!mobile) {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	} else if (mobile == undefined) {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	} else if (mobile == 'undefined') {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	}

	if (mobile === to_mobile) {
		vm.$u.toast(app2.$i18n.t('不能与自己聊天'));
		return false
	}
	
	console.log('public.js', {type: "detail",mobile: mobile,to_mobile: to_mobile})

	if ((to_mobile == 'undefined') || (to_mobile == undefined)) {
		to_mobile = 'customer001';
	}


	// #ifdef APP-PLUS
	if (iskf) {
		var userID = kfs[0]
	} else {
		var userID = PERFIX + to_mobile
	}

	const conversationID = `C2C${userID}`;
	TUIConversationService.getConversationProfile(conversationID)
		.then((res) => {
			console.log('createC2CConversation-success', res)
			TUIConversationService.switchConversation(
				res.data.conversation.conversationID
			);
			uni.navigateTo({
				url: '/TUIKit/components/TUIChat/index'
			});
		}).catch((err) => {
			uni.showToast({
				title: "The other party has not registered for a chat service",
				icon: 'none'
			})
			console.warn("打开会话失败", err.code, err.msg);									
		});
	// #endif

	// #ifdef WEB
	if (iskf) {
		var userID = kfs[0]
	} else {
		var userID = PERFIX + to_mobile
	}

	const conversationID = `C2C${userID}`;
	TUIConversationService.getConversationProfile(conversationID)
		.then((res) => {
			console.log('createC2CConversation-success', res)
			TUIConversationService.switchConversation(
				res.data.conversation.conversationID
			);
			uni.navigateTo({
				url: '/TUIKit/components/TUIChat/index'
			});
		}).catch((err) => {
			uni.showToast({
				title: "The other party has not registered for a chat service",
				icon: 'none'
			})
			console.warn("打开会话失败", err.code, err.msg);									
		});
	// #endif

	// #ifdef MP
	// 跳转IM - webview
	// 聊天的userID
	if (to_mobile == 'customer002') {
		to_mobile == 'customer001';
	}
	vm.$u.route({
		url: "/TUIKit/components/TUIConversation/index",
		params: {
			iskf,
			to_mobile,
			type: 'detail'
		}
	})
	// #endif
}

//实时获取胶囊位置
export function getCapsule() {
	return uni.getMenuButtonBoundingClientRect()
}




export const isVideo = (fileName) => {
	// 后缀获取
	let suffix = ''
	// 获取类型结果
	let result = false
	try {
		let flieArr = fileName.split('.')
		suffix = flieArr[flieArr.length - 1]
	} catch (err) {
		suffix = ''
	}
	// 图片格式
	let videoList = ['mp4', 'm2v', 'mkv', 'avi', 'rm', 'mpg', 'flv', 'rmvb'];
	// 进行图片匹配
	result = videoList.some(function(item) {
		return item === suffix
	})
	if (result) {
		result = true
		return result
	}
}